<script setup lang="ts">
import { ElRow, ElCol } from 'element-plus';
import { ref, onMounted, onUnmounted, watch } from 'vue';
import 'codemirror/mode/javascript/javascript.js';
import Codemirror from 'codemirror-editor-vue3';
import type { CmComponentRef } from 'codemirror-editor-vue3';
import type { Editor, EditorConfiguration } from 'codemirror';
import { DocumentEditor } from '@onlyoffice/document-editor-vue';
const scriptUrl = defineModel('scriptUrl');
const demoFileUrl = defineModel('demoFileUrl');
const demoConfigType = defineModel('demoConfigType');
const demoConfigMode = defineModel('demoConfigMode');
interface Props {
  scriptUrl?: string;
}

defineOptions({
  name: 'DataVailListWorksheetChange',
});

const props = withDefaults(defineProps<Props>(), {});

const getUuid = function () {
  return 'xxxxxxxxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

const VITE_ONLY_OFFICE_BASE_URL = import.meta.env.VITE_ONLY_OFFICE_BASE_URL;
const code = ref(``);
const containerRef = ref();
const cmRef = ref<CmComponentRef>();
const cmOptions: EditorConfiguration = {
  mode: 'text/javascript',
};

const onChange = (val: string, cm: Editor) => {
  // console.log(val);
  // console.log(cm.getValue());
};

const onInput = (val: string) => {
  // console.log(val);
};

const onReady = (cm: Editor) => {
  // console.log(cm.focus());
};

let containerWidth = 0;
let containerHeight = 0;
let documentEditorKey = ref('');
onMounted(() => {
  containerWidth = containerRef.value.parentNode.offsetWidth;
  containerHeight = containerRef.value.parentNode.offsetHeight;
  if (containerHeight > 800) {
    containerHeight = 800;
  }
  containerRef.value.style.height = containerHeight + 'px';
  setTimeout(() => {
    cmRef.value?.resize('100%', containerHeight);
  }, 1000);
  documentEditorKey.value = getUuid();
});

onUnmounted(() => {
  cmRef.value?.destroy();
});

watch(scriptUrl, async (newscriptUrl, oldscriptUrl) => {
  fetch(newscriptUrl)
    .then(function (data) {
      return data.text();
    })
    .then(function (data) {
      code.value = data;
    });

  if (window.DocEditor) {
    if (window.connector && window.connector.isConnected) {
      window.connector.disconnect();
    }
  }

  config.value.document.key = getUuid();
  config.value.document.url = demoFileUrl.value;
  config.value.document.type = demoConfigType.value;
  config.value.editorConfig.mode = demoConfigMode.value;
  documentEditorKey.value = config.value.document.key;
});

watch(demoFileUrl, async (newsDemoFileUrl, oldDemoFileUrl) => {});

let currentConnector = null;
const onDocumentReady = () => {
  console.log('onDocumentReady');
  code.value += '\n\nonDocumentReady\n';
  currentConnector = DocEditor.instances.docEditor.createConnector();
  window.connector = currentConnector;
  currentConnector.attachEvent('onWorksheetChange', function (address) {
    console.log('onWorksheetChange');
    console.log(address);
    Asc.scope = {
      address: address,
    };
    connector.callCommand(
      function () {
        let range = Api.GetRange(Asc.scope.address + ':' + Asc.scope.address);
        return range.GetValue();
      },
      function (value) {
        code.value += '\n\n变动单元格：' + address+'。当前值：'+ value + '\n';
      },
    );
  });
  setTimeout(() => {}, 1000);
};

var config = ref({
  type: 'desktop',
  // "type": "mobile",
  documentType: 'cell',
  historyList: {
    history: [],
    currentVersion: '1',
  },
  document: {
    title: 'test.xlsx',
    // url: "https://d2nlctn12v279m.cloudfront.net/assets/docs/samples/zh/demo.docx",
    url: '',
    permissions: {
      print: true,
      download: true,
      edit: true,
    },
    fileType: 'xlsx',
    key: getUuid(),
  },
  editorConfig: {
    customization: {
      autosave: false,
      compactToolbar: false,
      forcesave: true,
      toolbarNoTabs: true,
      help: false,
      compactHeader: false,
      hideRightMenu: true,
      plugins: true,
      uiTheme: 'theme-light',
    },
    mode: 'edit',
    callbackUrl:
      'https://api.docs.onlyoffice.com/dummyCallback',
    lang: 'zh-CN',
    user: {
      name: '曹瑞剑雄',
      id: '104',
    },
  },
});

const init = function () {
  console.log(scriptUrl);
  fetch(scriptUrl.value)
    .then(function (data) {
      return data.text();
    })
    .then(function (data) {
      code.value = data;
    });

  if (window.DocEditor) {
    // if (connector) {
    //   connector.disconnect();
    // }
  }
  config.value.document.key = getUuid();
  config.value.document.url = demoFileUrl.value;
  config.value.document.type = demoConfigType.value;
  config.value.editorConfig.mode = demoConfigMode.value;
  documentEditorKey.value = config.value.document.key;
};
init();
</script>

<template>
  <di class="onlyoffice_demo_container" ref="containerRef">
    <el-row>
      <el-col :span="11">
        <Codemirror
          v-model:value="code"
          :options="cmOptions"
          border
          ref="cmRef"
          width="100%"
          height="100%"
          @change="onChange"
          @input="onInput"
          @ready="onReady"
        >
        </Codemirror>
      </el-col>
      <el-col :span="13">
        <DocumentEditor
          v-if="demoFileUrl && config.document.url"
          id="docEditor"
          :documentServerUrl="VITE_ONLY_OFFICE_BASE_URL"
          :config="config"
          :events_onDocumentReady="onDocumentReady"
        />
      </el-col>
    </el-row>
  </di>
</template>

<style scoped>
.onlyoffice_demo_container {
  width: 100%;
  height: 100%;
  display: inline-block;
}
</style>
